package com.yupi.springbootinit.statemachine.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yupi.springbootinit.statemachine.core.StateTransitionRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * 状态转换记录Mapper
 */
@Mapper
public interface StateTransitionRecordMapper extends BaseMapper<StateTransitionRecord> {
    
    /**
     * 统计指定时间范围内的状态转换次数
     */
    @Select("SELECT entity_type, COUNT(*) as count " +
            "FROM state_transition_record " +
            "WHERE create_time >= #{startTime} AND create_time <= #{endTime} " +
            "GROUP BY entity_type")
    List<Map<String, Object>> countTransitionsByEntityType(@Param("startTime") String startTime, 
                                                           @Param("endTime") String endTime);
    
    /**
     * 统计状态转换成功率
     */
    @Select("SELECT entity_type, " +
            "COUNT(*) as total_count, " +
            "SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as success_count " +
            "FROM state_transition_record " +
            "WHERE create_time >= #{startTime} AND create_time <= #{endTime} " +
            "GROUP BY entity_type")
    List<Map<String, Object>> getTransitionSuccessRate(@Param("startTime") String startTime, 
                                                       @Param("endTime") String endTime);
    
    /**
     * 查询转换耗时超过阈值的记录
     */
    @Select("SELECT * FROM state_transition_record " +
            "WHERE duration > #{threshold} " +
            "ORDER BY duration DESC " +
            "LIMIT #{limit}")
    List<StateTransitionRecord> findSlowTransitions(@Param("threshold") Long threshold, 
                                                   @Param("limit") Integer limit);
}